﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using EPiServer.Web.Hosting;
using System.IO;
using System.Web.Hosting;

namespace EPiServer.Research.MobileCenter
{
    /// <summary>
    /// Image upload is a class used by the MobileCenter to send pictures to a specific location
    /// It uses the viewstate to send in bytes to a asp fileupload control which is saved in a tmp global
    /// </summary>
    public partial class ImageUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (fu.HasFile)
            {
                //one image at a time, uniqueid

                string destinationPath = "/Global/MobileCenterUploadedImages/";
                if (!HostingEnvironment.VirtualPathProvider.DirectoryExists(destinationPath))
                {
                    UnifiedDirectory.CreateDirectory(destinationPath);
                }

                var dir = System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetDirectory(destinationPath) as UnifiedDirectory;
                dir.BypassAccessCheck = true;
                byte[] photo = fu.FileBytes;
                 UnifiedFile uFile;
                 if (dir.GetFiles().Length > 0)
                 {
                     uFile = dir.GetFiles()[0];
                 }
                 else
                 {
                     uFile = dir.CreateFile("tmpMobileCenterImage.png");
                 }
                Stream s = uFile.Open(FileMode.Create);
                int numBytesToRead = photo.Length;
                s.Write(photo, 0, photo.Length);
                s.Close();
                dir.BypassAccessCheck = false;

            }
        }
    }
}
